<?php    	
	session_start();
	class Captcha 
    {
        public static function Generate() 
        {            
            $colors =  array ('0' => '145',
                    '1' => '204',
                    '2' => '177',
                    '3' => '184',
                    '4' => '199',
                    '5' => '255');
                    
            $image = imagecreatetruecolor(165, 50);
            $bg = imagecolorallocate($image, 255, 255, 255);
            imagefill($image, 10, 10, $bg);

            for ($x=0; $x < 165; $x++)
            {
                for ($y=0; $y < 50; $y++)
                {
                    $random = mt_rand(0 , 5);
                    $temp_color = imagecolorallocate($image, $colors[$random], $colors[$random], $colors[$random]);
                    imagesetpixel($image, $x, $y , $temp_color);
                }
            }

            $char_color = imagecolorallocatealpha($image, 0, 0, 0, 70);

            $string = md5(microtime() * mktime());
            $text = substr($string, 0, 6);
            $_SESSION['code'] = $text;            
            $x1 = 0;
            $x2 = 10;            
            $font = dirname( __FILE__ ) . '/arial.ttf';
            $font_size = 20;

            for($i = 0; $i < 6; $i++) 
            {    
                $x1 = $x1 + 20;
                $x2 = $x2 + 20;
                $char = $text[$i];
                $random_x = mt_rand($x1, $x2);
                $random_y = mt_rand(25, 45);
                $random_angle = mt_rand(-20, 20);
                imagettftext($image, $font_size, $random_angle, $random_x, $random_y, $char_color, $font, $char);
            }
            
            ob_start();
            imagepng($image);
            imagedestroy($image);
            printf('<img src="data:image/png;base64,%s" alt="captcha"/>', base64_encode(ob_get_clean()));            
        }
        
        public static function Verify($text) 
        {        	
            if($text == $_SESSION['code']) 
            {
                unset($_SESSION['code']);
                return true;                
            }
            else
                return false;
        }
        
        public static function Refresh() 
        {
            self::Generate();
        }
    }